var messageDAO = require('./models/message.js');
var msgpack = require('./helper/framedmsgpack.js');

/** 推送业务
 * [pushMsg description]
 * @param  {[type]} req         [description]
 * @param  {[type]} res         [description]
 * @param  {[type]} config      [description]
 * @param  {[type]} msg         [description]
 * @param  {[type]} connections [description]
 * @return {[type]}             [description]
 */
function pushMsg(req, res, config, deviceId, msg, connections) {

  if (config.APP_ID !== req.body.appId || config.APP_SECRET !== req.body.secret || !deviceId || deviceId === '') {
    res.status(401).json({
      code: 401,
      status: 'Unauthorized',
      message: 'request validation fail.'
    });
    return;
  }
  // 由于bodyParse中间件解析本身就是json对象就没必要再次装换
  if (!(msg instanceof Object)) {
    msg = eval("(" + msg + ")"); // 转换msg对象 JSON.parse(msg)
  }
  // http://m.changan.com.cn/instant/pushMsg (POST)
  /* appId: '43ea5ef81c2e036a93de068f7dd739be'
   * secret: 'ab3194ab-c4c9-4b1f-9a99-5a625bae2c60'
   * msg: '{ "id": '1', "title":"公告", "messageType":"MODULE", "extras":{"moduleIdentifer":"com.foss.announcement"}}'
   * deviceId: '00000000-4df8-d963-3b64-93f651a1e20a'
   */
  var message = {
    msgId: msg.id,
    msgType: msg.messageType,
    title: msg.title,
    target: deviceId,
    isWrap: msg.isWrap
  }
  if (msg.extras) { // 存在扩展信息情况，例如推送公告
    message.extras = msg.extras;
  }
  console.log('step1 保存日志：' + message.msgId);
  /** 根据设备发送msg */
  console.log('step2 发送消息 --> %s: %s, 队列长度：%s', (typeof deviceId), deviceId, connections.keys.length);
  var socket = connections.get(deviceId);
  if (socket) {
    // mongo更新成功状态
    message.receive = true;
    messageDAO.save(message, function(err) {
      if (err) {
        console.log('插入message对象异常：' + err);
      }
      socket.write(msgpack.packWithType(msg, 1)); // 推送给客户端APP
      res.status(200).json({
        code: 200,
        status: 'sucess',
        message: '推送成功!'
      });
    });
  } else {
    console.log('此设备未保持长连接，没关系，登录长连接后它会去平台拉取离线消息！');
    // mongo更新失败状态
    message.receive = false;
    messageDAO.save(message, function(err) {
      if (err) {
        console.log('插入message对象异常：' + err);
      }
    });
    res.status(200).json({
      code: 304,
      status: 'failure',
      message: '推送失败!原因：此设备未保持长连接。'
    });
  }
}


//######## commonjs interface #################
module.exports = function apiContructor(app, connections, qqwry, config) {

  app.get("/instant/connections", function(req, res) {
    console.log('\n\n--------------------------------------------------------');
    var size = connections.size();
    res.status(200).json({
      code: 200,
      status: '√',
      message: '彩蛋 ≈≈ connections size：' + size
    });

  });

  app.post('/instant/pushMsg', function(req, res) {
    console.log('\n--------------------------------------------------------');
    console.log('\n--------------------------------------------------------');
    var ip = req.ip;
    if (qqwry)
      ip = qqwry.searchIP(req.ip); // 解析ip地址 eg：{ ip: '115.28.1.119', Country: '北京市', Area: '万网IDC机房' }

    console.log('Request：request coming：%s, %s, %s', ip.ip === undefined ? ip : ip.ip,
      ip.Country === undefined ? '' : ip.Country,
      ip.Area === undefined ? '' : ip.Area);
    console.log('Request body:');
    console.log(req.body); // msg应该带有设备id

    // step1 获取msg deviceId
    var msg = req.body.msg;
    var deviceId = req.body.deviceId;
    pushMsg(req, res, config, deviceId, msg, connections);
  });
}